//
//  HomeMessageController.m
//  WeiboSpace
//
//  Created by  linan4 on 12-3-3.
//  Copyright 2012 __MyCompanyName__. All rights reserved.
//

#import "HomeMessageController.h"
#import "WeiboDetailController.h"
#import "TransparentButton.h"
#import "StatusCell.h"
#import "ThumbImageView.h"
#import "WSNavBarTitleView.h"

//appkey and appkeysecret
#define APPEKEY @"1063104162"
#define APPKEY_SECRET @"1813bb6ecbb80da77e839c4b393193ae"
#define Key_AccessToken @"Accesstoken"

@implementation HomeMessageController
@synthesize accessToken;
@synthesize weiboTableView;
#pragma mark -
#pragma mark View lifecycle
- (void)viewDidLoad {
    [super viewDidLoad];
	
	//标题，左右NaviBar
	self.navigationItem.title = @"HomeMessage";
	
	UIBarButtonItem *newMsgButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCompose
																				  target:self action:@selector(newMessage)];
	self.navigationItem.rightBarButtonItem = newMsgButton;
	[newMsgButton release];
	
	UIBarButtonItem *reloadButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh
																				  target:self action:@selector(reload)];
	self.navigationItem.leftBarButtonItem = reloadButton;
	[reloadButton release];
    
    //NavigationBar的其它
    WSNavBarTitleView *_titleView = [[WSNavBarTitleView alloc]initWithFrame:CGRectMake(0, 0, 180, 40)];
	self.navigationItem.titleView = _titleView;
    [_titleView release];
    
    //设置UITableView
    UITableView *_tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, self.view.bounds.size.height - 44) style:UITableViewStylePlain];
    [_tableView setBackgroundColor:[UIColor redColor]];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    self.weiboTableView = _tableView;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    [_tableView release];
    
	//配置WeiboSDK
	 sdkEngine = [[WBEngine alloc] initWithAppKey:APPEKEY appSecret:APPKEY_SECRET];
    [sdkEngine setRootViewController:self];
    [sdkEngine setDelegate:self];
    [sdkEngine setRedirectURI:@"http://weibo.com"];
    [sdkEngine setIsUserExclusive:NO];

	//创建timeline字典
	timeLine = [[NSMutableArray alloc]init];
	
	//创建，初始化HttpEngine
	weiboEngine = [[WeiboHttpEngine alloc] InitWeiboSpaceWithDelegate:self];
    
    self.accessToken = [[NSUserDefaults standardUserDefaults]objectForKey:Key_AccessToken];
}

- (void)viewDidUnload {
	
	[weiboEngine release],weiboEngine = nil;
	[sdkEngine release],sdkEngine = nil;
	[timeLine release],timeLine = nil;
    self.weiboTableView = nil;
    

}

-(void)doRefreshOperation
{
   [self requestTimeLine:nil maxID:nil requestCount:10];
}

#pragma mark -
#pragma mark Member Funtions

- (void)newMessage
{
	
}

- (void)reload
{
    //NSLog(@"table contentOffset:x=%@,y=%@",_tableView.contentOffset.x,_tableView.contentOffset.y);
	//test
	//self.accessToken = @"2.00jMcRMC1xfwJBef63ee15cadHJUEC";
	//test
    //self.accessToken = nil;
	if (self.accessToken == nil||self.accessToken.length==0) {
		//TODO:跳转到登陆
		[sdkEngine logIn];
	}
	else {
		//刷新数据
		[self requestTimeLine:nil maxID:nil requestCount:10];
		
	}
	
}

- (void)requestTimeLine:(NSString*)sinceId maxID:(NSString*)maxId requestCount:(int)count
{
	//这里
	//NSString *strCount = [NSString stringWithFormat:@"%i",count];
	//NSDictionary *urlParams = [[NSDictionary alloc] initWithObjectsAndKeys:sinceId, @"since_id",maxId,@"max_id",strCount,@"count", nil];
    NSMutableDictionary *urlParams = [NSMutableDictionary dictionaryWithCapacity:0];
    if (sinceId) {
        [urlParams setObject:sinceId forKey:@"since_id"];
    }
	
	if (maxId) {
        [urlParams setObject:maxId forKey:@"max_id"];
    }
	[weiboEngine SendHttpRequest:Get requestUrl:@"2/statuses/friends_timeline.json" urlParams:urlParams bodyParams:nil accessToken:self.accessToken];

}

#pragma mark -
#pragma mark Table view delegate
//这里可以挪到上级或者公有
- (UITableViewCell *)configThisIdentifier:(NSString *)identifier {
	
	if (@"NodateCell"==identifier) {
		UITableViewCell *uiCell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier]autorelease];
		uiCell.textLabel.textAlignment = UITextAlignmentCenter;
		uiCell.textLabel.font = [UIFont systemFontOfSize:16];
		return uiCell;
	}
	else{
		
		StatusCell *_statusCell = [[[StatusCell alloc]initCell:ShowAllStuff delegate:self] autorelease];;
		return _statusCell;
	}
    
}

-(void) FillCellElements:(UITableViewCell*) cell forIndexPath:(NSIndexPath*) indexPath{
	
	NSUInteger rowIndex = [indexPath row];
	if(nil == timeLine || 0 == [timeLine count]){
		return;
	}
    
	if (rowIndex <[ timeLine count]) {
		
		NSDictionary *statusData = [timeLine objectAtIndex:rowIndex];
		
		StatusCell *statuscell = (StatusCell*)cell;
		[statuscell updateCell:statusData];
		
	}
	else {
		cell.textLabel.text = @"Load More...";
	}
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	
    NSString *identifier = timeLine != nil && indexPath.row < [timeLine count]? @"indentifer": @"NodateCell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) 
	{
		//配置cell
        cell = [self configThisIdentifier:identifier];		 
    }
	
	[self FillCellElements:cell forIndexPath:indexPath];
	cell.contentView.backgroundColor = [UIColor whiteColor];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	if(timeLine == nil||[timeLine count] == 0)
		return;
	
	if(indexPath.row < [timeLine count])
	{
		
		NSDictionary * status = [timeLine objectAtIndex:indexPath.row];
		
		//push to navigation stack
		WeiboDetailController *msgView = [[WeiboDetailController alloc] InitViewWithStatus:status];
        msgView.hidesBottomBarWhenPushed = YES;
		[self.navigationController pushViewController:msgView animated:YES];
		[msgView release];
	}
	else
	{
		if (timeLine!=nil&&[timeLine count]>0) {
			NSDictionary * status = [timeLine objectAtIndex:[timeLine count]-1];
			
			NSString *maxId = [status objectForKey:@"id"];
			if (maxId!=nil) {
				[self requestTimeLine:nil maxID:maxId requestCount:10];
			}
		}
	}
    
}

//控制高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
	
	if(indexPath.row >= [timeLine count]) 
		return 50;
	
	UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
	CGFloat height = cell.frame.size.height;
	return height;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
	return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	
	if (nil != timeLine&&[timeLine count] > 0) {
		return [timeLine count]+1;
	}
	else {
		return 0;
	}
	
}


#pragma mark -
#pragma mark WBEngine delegage
- (void)engineDidLogIn:(WBEngine *)engine
{
    //保存到本地
    [[NSUserDefaults standardUserDefaults]setObject:engine.accessToken forKey:Key_AccessToken];
    [[NSUserDefaults standardUserDefaults]synchronize];
    
	self.accessToken = engine.accessToken;
	[self reload];
}

#pragma mark WeiboHttpDelegate
-(void) DealJsonDataFinished:(id)response
{
	if ([response isKindOfClass:[NSDictionary class]])
    {
		NSDictionary *dict = (NSDictionary *)  response;
        [timeLine addObjectsFromArray:[dict objectForKey:@"statuses"]];
		
		//重新加载
		[weiboTableView reloadData];
	}
}

-(void) DealJsonDataException:(NSError*)err{
    //TODO:
}

#pragma mark StatusCellDelegate
-(void)CellButtonClicked:(NSString *)mark{
	
	//push to navigation stack    
    CGRect rect = [[UIScreen mainScreen] bounds];
	ThumbImageView *imageView = [[ThumbImageView alloc]initWithFrame:rect withimageurl:mark];
    imageView.alpha = 0.0f;
    [self.view.window addSubview:imageView];
    [imageView fadein];
    [imageView release];
}

#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc. that aren't in use.
}

- (void)dealloc {	 
	[accessToken release];
	[timeLine release];
	[weiboEngine release];
	[sdkEngine release];
    self.weiboTableView = nil;
    [super dealloc];
}


@end

